<?php

namespace App\Modules\Admin\Controllers;


use App\Models\Communities;
use App\Models\District;
use App\Models\Resource;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class CommunitiesController extends Controller
{
    public function index(Request $request)
    {
        $info = Communities::with('city','county')->orderBy('created_at','desc')->paginate($this->pageSize);
        return view('admin::communities.index', ['info' => $info]);
    }

    public function get()
    {
        return response()->json(Resource::query()->get());
    }

    public function first(Request $request)
    {
        $id = $request->id;
        return response()->json(District::find($id));
    }

    public function save(Request $request)
    {
        $params = $request->all();
        if(in_array($params['province_id'],[1,2,3,4])) {
            $params['county_id'] = $params['city_id'];
        }
        $rule   = [
            'name' => 'required'
        ];
        Validator::make($params, $rule)->validate();
        if (isset($params['id'])) {
            Communities::query()->where('id', $params['id'])->update($params);
        } else {
            Communities::create($params);
        }
    }

    public function form(Request $request)
    {
        $id = $request->id;
        $root_districts = District::where('parentid', 0)->get();
        $params['root_districts'] = $root_districts;
        if (isset($id)) {
            $community = Communities::where('id',$id)->first();
            $params['community'] = $community;
            $params['id'] = $id;
        } else {

        }
        return view('admin::communities.form', $params);
    }

    public function delete(Request $request)
    {
        Communities::destroy($request->input('id'));
    }
}
